//
//  BlueManager.m
//  PerDemo
//
//  Created by 王锋 on 2017/12/26.
//  Copyright © 2017年 王锋. All rights reserved.
//

#import "BlueManager.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import <UIKit/UIKit.h>
#import "AES128Util.h"

@interface BlueManager ()<CBPeripheralManagerDelegate>

@property(nonatomic, strong) CBPeripheralManager *peripheralManager;

@property(nonatomic, copy) NSString *mesg;

@property(nonatomic, assign, readwrite) NSInteger num;

@end
@implementation BlueManager

+ (instancetype)standBlueManager{
    static BlueManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        [manager setup];
    });
    return manager;
}

- (void)setup{
    self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey : @YES}];
    self.mesg = @"ff1b2c";
}

- (void)changedWithNum:(NSInteger)num temper:(NSInteger)temper type:(BlueManagerNum)type{
    switch (type) {
        case BlueManagerNumAdd:
        {
            if (self.status == BlueManagerTypeTemperature) {
                if (self.temper >= 255) return;
                if (self.temper == 0) {
                    self.temper += 15;
                }else{
                    self.temper += temper;
                }
            }else if (self.status == BlueManagerTypeLight){
                if (self.num >= 255) return;
                if (self.num == 0) {
                    self.num += 15;
                }else{
                    self.num += num;
                }
            }
        }
            break;
        case BlueManagerNumSubtract:
        {
            if (self.status == BlueManagerTypeLight) {
                if (self.num <= 0) return;
                if (self.num <= num) {
                    self.num = 0;
                }else{
                    self.num -= num;
                }
            }else if (self.status == BlueManagerTypeTemperature){
                if (self.temper <= 0) return;
                if (self.temper <= temper) {
                    self.temper = 0;
                }else{
                    self.temper -= temper;
                }
            }
        }
            break;
        case BlueManagerNumAddSpecific:
        {
            self.num = num;
            self.temper = temper;
        }
            break;
        case BlueManagerNumOther:
        {
            
        }
            break;
    }
    [self.peripheralManager stopAdvertising];
    NSString *numStr = [AES128Util stringWithHexNumber:self.num];
    NSString *tempStr = [AES128Util stringWithHexNumber:self.temper];
    if (tempStr.length <= 1) {
        tempStr = [NSString stringWithFormat:@"0%@",tempStr];
    }
    if (numStr.length <= 1) {
        numStr = [NSString stringWithFormat:@"0%@",numStr];
    }
    NSString *nameValue;
    if (self.status == BlueManagerTypeLight) {
        nameValue = [NSString stringWithFormat:@"%@02%@",self.mesg,numStr];
    }else if (self.status == BlueManagerTypeTemperature){
        nameValue = [NSString stringWithFormat:@"%@03%@",self.mesg,tempStr];
    }else{
        nameValue = [NSString stringWithFormat:@"%@04%@%@",self.mesg,numStr,tempStr];
    }
    [self.peripheralManager startAdvertising:@{CBAdvertisementDataServiceUUIDsKey : @[],
                                               CBAdvertisementDataLocalNameKey : nameValue}];
}

- (void)alert{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"打开蓝牙来连接到配件" preferredStyle:(UIAlertControllerStyleAlert)];
    // 是否跳转到蓝牙界面
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"设置" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    // 创建按钮
    // 注意取消按钮只能添加一个
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    // 添加按钮 将按钮添加到UIAlertController对象上
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    
    // 将UIAlertController模态出来 相当于UIAlertView show 的方法
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - CBPeripheralManagerDelegate -

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    if (@available(iOS 10.0, *)) {
        if (peripheral.state != CBManagerStatePoweredOn) {
            NSLog(@"蓝牙未开启");
            if (peripheral.state == CBManagerStatePoweredOff) {
                [self alert];
            }
        }else{
            //发广播
            NSLog(@"发广播");
            [self.peripheralManager startAdvertising:@{CBAdvertisementDataServiceUUIDsKey : @[], CBAdvertisementDataLocalNameKey : @"ff1b2c0200"}];
        }
    } else {
        // Fallback on earlier versions
        if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
            NSLog(@"蓝牙未开启");
            if (peripheral.state == CBPeripheralManagerStatePoweredOff) {
                [self alert];
            }
        }else{
            //发广播
            NSLog(@"发广播");
            [self.peripheralManager startAdvertising:@{CBAdvertisementDataServiceUUIDsKey : @[], CBAdvertisementDataLocalNameKey : @"ff1b2c0200"}];
        }
    }
}

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
    if (error != nil) {
        NSLog(@"广播错误:%@",error);
    }else{
        NSLog(@"广播成功");
    }
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
    NSLog(@"--%s-----",__FUNCTION__);
}

@end
